//
//  chooseStation.m
//  ElektroM
//
//  Created by Michael on 16.10.09.
//  Copyright 2009 Artgruppe inc. All rights reserved.
//

#import "chooseStation.h"
#import "railwaysController.h"


@implementation chooseStation
@synthesize toolbar, Back, table, searchBar;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	[toolbar setTitle:NSLocalizedString(@"StationSelect", @"")];
	[Back setTitle:NSLocalizedString(@"Back", @"")];
	nSelected=-1;
}
-(void)setStationsInfo:(NSString**)st withCount:(int)count andRailwaysController:(railwaysController*)controller
{
	nStationsCount=count;
	stations=st;
	myMaster=controller;
	[table reloadData];
}


-(void)setStationsInfoAsNSArray:(NSArray*)aiSt 
		      withCount:(int)count 
	  		andRailwaysController:(railwaysController*)controller
{
	nStationsCount=count;
	_aiStations=aiSt;
	myMaster=controller;
	[table reloadData];
}

-(int) getSelected
{
	return nSelected;
}


-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	//printf("Search %s\n", [searchText UTF8String]);
	if([searchText length]==0)return;	
	_bSearchInProgress=true;
	/*
	if(strStationsSearched==nil)
		strStationsSearched=(NSString**)malloc(sizeof(NSString)*nStationsCount);
	 */
	if(indexesToFoundedStations==nil)
		indexesToFoundedStations=(int*)malloc(sizeof(int)*nStationsCount);

	_nSearchedStations=0;	
	for(int i=0; i<nStationsCount; i++){
		//[stations[i] retain];
		//NSString* compare=[NSString stringWithString:stations[i]];		
		//NSRange range=[stations[i] rangeOfString:searchText options:NSCaseInsensitiveSearch];
		NSRange range=[[_aiStations 
		    objectAtIndex:i] rangeOfString:searchText options:NSCaseInsensitiveSearch];
		if(range.location!=NSNotFound){
			//strStationsSearched[_nSearchedStations++]=stations[i]/*[NSString stringWithString:stations[i]]*/;
			indexesToFoundedStations[_nSearchedStations++]=i;			
		}
	}
	[table reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
	//printf("Cancel clicked!\n");
	_bSearchInProgress=false;	
	/*
	if(indexesToFoundedStations!=nil)
		free(indexesToFoundedStations);		
	 
	if(strStationsSearched!=nil)
		free(strStationsSearched);
	 */
	[table reloadData];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	//printf("in number of rows: nNeededForMeCount %d\n", nNeededForMeCount);	
	if(_bSearchInProgress)
	{		
		//printf("Searching.. Count:%d\n", _nSearchedStations);		
		return _nSearchedStations;
	}
	else
	{		
		//printf("Not Searching.. Count:%d\n", nStationsCount);
		return [_aiStations count];
		//return nStationsCount;
	}
		
}

- (UITableViewCell *)tableView:(UITableView *)tableViewMy cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *kCellIdentifier = @"cellID";
	
		
	UITableViewCell *cell = [tableViewMy dequeueReusableCellWithIdentifier:kCellIdentifier];
	if (!cell)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCellIdentifier] autorelease];
        
		cell.accessoryType = UITableViewCellAccessoryNone;
        
        cell.textLabel.backgroundColor = [UIColor clearColor];
		cell.textLabel.opaque = NO;
		cell.textLabel.textColor = [UIColor blackColor];
		cell.textLabel.highlightedTextColor = [UIColor whiteColor];
		cell.textLabel.font = [UIFont boldSystemFontOfSize:18];
    }    
	// get info about time table here...	
	if(!_bSearchInProgress){
		//printf("Getting info about station: %d\n", indexPath.row);
		cell.textLabel.text = [_aiStations objectAtIndex: indexPath.row];
		    //stations[indexPath.row];
	}
	else
		cell.textLabel.text = [_aiStations objectAtIndex: indexesToFoundedStations[indexPath.row]];
		    //stations[indexesToFoundedStations[indexPath.row]];	
	 
	//cell.textLabel.text = stations[indexPath.row];
    //cell.detailTextLabel.text = @"";
	
	return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{  		
	if(!_bSearchInProgress){
		nSelected=indexPath.row;		
	}
	else{
		nSelected=indexesToFoundedStations[indexPath.row];		
	}
 
	//nSelected=indexPath.row;
	//printf("Found: %d\n", nSelected);
	[myMaster setSelection:nSelected];	
	/*
	if(indexesToFoundedStations!=nil){
		free(indexesToFoundedStations);	
		indexesToFoundedStations=nil;
	}
	 */
	
	/*
	if(strStationsSearched!=NULL)
		free(strStationsSearched);
	 */
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
	[self.table deselectRowAtIndexPath:self.table.indexPathForSelectedRow animated:NO];
}

-(IBAction) goBack
{
	if(indexesToFoundedStations!=nil){
		free(indexesToFoundedStations);
		indexesToFoundedStations=nil;
	}
	[self.parentViewController dismissModalViewControllerAnimated:YES];	
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	
	self.table=nil;	
	self.toolbar = nil;	
	self.Back = nil;
}


- (void)dealloc {
	[table release];
	[toolbar release];
	[Back release];
    [super dealloc];
}


@end
